package javabase.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

public class AIOServer {

	public AIOServer() throws IOException {
		final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(8888));
		listener.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() {

			@Override
			public void completed(AsynchronousSocketChannel result, Void attachment) {
				listener.accept(null, this);
				handle(result);
			}


			@Override
			public void failed(Throwable exc, Void attachment) {
				System.out.println("failed");
			}
		});
	}
	
	private void handle(AsynchronousSocketChannel result) {
		ByteBuffer buffer = ByteBuffer.allocate(100);
		try {
			result.read(buffer).get();
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		buffer.flip();
		System.out.println(buffer.get());
	}
	
	public static void main(String[] args) throws IOException, InterruptedException {
		AIOServer server = new AIOServer();
		System.out.println("server started ");
		Thread.sleep(Long.MAX_VALUE);
	}
	
}
